from django.shortcuts import render

# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.authentication import BasicAuthentication, SessionAuthentication
from rest_framework.filters import SearchFilter, OrderingFilter
from rest_framework.mixins import ListModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from rest_framework_simplejwt.authentication import JWTAuthentication

from order.filter import OrderFilter
from order.models import Order
from order.serializers import OrderSerializer


class OrderListViewSet(ListModelMixin, GenericViewSet):
    serializer_class = OrderSerializer

    # 局部添加定制身份权限认证
    # 设置需要身份验证的类
    authentication_classes = [BasicAuthentication, SessionAuthentication, JWTAuthentication]
    # 全类权限认证
    permission_classes = [IsAuthenticated, ]

    # 过滤器可多个
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]

    # Backend过滤字段设置
    filterset_fields = ['total', 'number']

    # 搜索过滤字段设置
    search_fields = ['number', ]

    # 排序字段设置
    ordering_fields = ['number', 'total']

    # 引用自定义过滤器
    filter_class = OrderFilter

    # 过滤
    def get_queryset(self):
        """
        Optionally restricts the returned purchases to a given user,
        by filtering against a `username` query parameter in the URL.
        """
        # queryset = Order.objects.all()
        # username = self.request.query_params.get('username')
        # if username is not None:
        #     queryset = queryset.filter(user=self.request.user)
        orders = Order.objects.filter(user=self.request.user)

        return orders
